/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.logistics.service.ladingbill;

import com.jeesite.common.collect.SetUtils;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.file.utils.FileUploadUtils;
import com.jeesite.modules.financial.entity.arrivalreminder.ArrivalReminder;
import com.jeesite.modules.financial.service.arrivalreminder.ArrivalReminderService;
import com.jeesite.modules.logistics.dao.ladingbill.LadingBillDao;
import com.jeesite.modules.logistics.dao.ladingbill.LadingBillDetailDao;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBill;
import com.jeesite.modules.logistics.entity.ladingbill.LadingBillDetail;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentActual;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedActual;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * 提单Service
 * @author LV
 * @version 2021-03-09
 */
@Service
@Transactional(readOnly=true)
public class LadingBillService extends CrudService<LadingBillDao, LadingBill> {
	
	@Autowired
	private LadingBillDetailDao ladingBillDetailDao;
	@Autowired
	private CodeRuleService codeRuleService;
	@Autowired
	private ArrivalReminderService arrivalReminderService;
	@Autowired
	private ServiceOrderService serviceOrderService;
    @Autowired
    private TadvancesReceivedService tadvancesReceivedService;
    @Autowired
    private TapService tapService;
    @Autowired
    private TarService tarService;
    @Autowired
    private TprepaymentService tprepaymentService;


	/**
	 * 获取单条数据
	 * @param ladingBill
	 * @return
	 */
	@Override
	public LadingBill get(LadingBill ladingBill) {
		LadingBill entity = super.get(ladingBill);
		if (entity != null){
			LadingBillDetail ladingBillDetail = new LadingBillDetail(entity);
			ladingBillDetail.setStatus(LadingBillDetail.STATUS_NORMAL);
			entity.setLadingBillDetailList(ladingBillDetailDao.findList(ladingBillDetail));
		}
		return entity;
	}
	
	/**
	 * 查询分页数据
	 * @param ladingBill 查询条件
	 * @param ladingBill.page 分页对象
	 * @return
	 */
	@Override
	public Page<LadingBill> findPage(LadingBill ladingBill) {
		return super.findPage(ladingBill);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param ladingBill
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void save(LadingBill ladingBill) {
	    if (ladingBill.getIsNewRecord()){
	        ladingBill.setLadingBillCode(codeRuleService.getCode("ladingbill"));
        }
		super.save(ladingBill);
	    if (ladingBill.getIsNewRecord()){
	        codeRuleService.updateCurrentNumber("ladingbill");
        }
        // 保存上传图片
        FileUploadUtils.saveFileUpload(ladingBill.getId(), "ladingBill_image");
		// 保存上传附件
		FileUploadUtils.saveFileUpload(ladingBill.getId(), "ladingBill_file");
		// 保存 LadingBill子表
		for (LadingBillDetail ladingBillDetail : ladingBill.getLadingBillDetailList()){
			if (!LadingBillDetail.STATUS_DELETE.equals(ladingBillDetail.getStatus())){
				ladingBillDetail.setLadingBillId(ladingBill);
				if (ladingBillDetail.getIsNewRecord()){
					ladingBillDetailDao.insert(ladingBillDetail);
				}else{
					ladingBillDetailDao.update(ladingBillDetail);
				}
			}else{
				ladingBillDetailDao.delete(ladingBillDetail);
			}
		}

		// 到单提醒 回写
        ArrivalReminder arrivalReminder = arrivalReminderService.get(ladingBill.getArrivalReminderCode());
        arrivalReminder.setLadingBillCode(ladingBill.getLadingBillId());
        arrivalReminderService.save(arrivalReminder);

        List<LadingBillDetail> ladingBillDetails = ladingBill.getLadingBillDetailList();
		// 服务订单 回写
        ServiceOrder serviceOrder = serviceOrderService.get(ladingBill.getServiceOrderId());
        List<ServiceOrderDetail> serviceOrderDetailList = serviceOrder.getServiceOrderDetailList();
        for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
            for (ServiceOrderDetail serviceOrderDetail : serviceOrderDetailList) {
                if (ladingBillDetail.getRowNumber().equals(serviceOrderDetail.getRowNumber())){
                    if (StringUtils.isEmpty(serviceOrderDetail.getFrameNumber())){
                        serviceOrderDetail.setFrameNumber(ladingBillDetail.getFrameNumber());
                    }
                    if (StringUtils.isEmpty(serviceOrderDetail.getEngineNumber())){
                        serviceOrderDetail.setEngineNumber(ladingBillDetail.getEngineNumber());
                    }
                    if (serviceOrderDetail.getProductionDate() != null){
                        serviceOrderDetail.setProductionDate(ladingBillDetail.getProductionDate());
                    }
                    if (StringUtils.isEmpty(serviceOrderDetail.getFactory())){
                        serviceOrderDetail.setFactory(ladingBillDetail.getFactory());
                    }
                    if (StringUtils.isEmpty(serviceOrderDetail.getTireSize())){
                        serviceOrderDetail.setTireSize(ladingBillDetail.getTireSize());
                    }
                    if (StringUtils.isEmpty(serviceOrderDetail.getSeatNumber())){
                        serviceOrderDetail.setSeatNumber(ladingBillDetail.getSeatNumber());
                    }
                    serviceOrderDetail.setLogisticsStatus(ladingBillDetail.getDetailStatus());
                    serviceOrderDetail.setEngineNumber(ladingBillDetail.getEngineNumber());
                    serviceOrderDetail.setLadingBillId(ladingBill.getLadingBillId());
                }
            }
        }
        serviceOrderService.save(serviceOrder);

        // 车架号去重校验
        /*Set < String > set = SetUtils.newHashSet();
        Integer detailFramerCount = 0;
        for (ServiceOrderDetail serviceOrderDetail : serviceOrderService.findListDetail(new ServiceOrderDetail())) {
            if (StringUtils.isNotEmpty(serviceOrderDetail.getFrameNumber())) {
                set.add(serviceOrderDetail.getFrameNumber());
                detailFramerCount++;
            }
        }
        if (detailFramerCount != set.size()) {
            throw new RuntimeException("存在相同的车架号！");
        }*/

        // 预收费用 回写
        if (StringUtils.isNotEmpty(serviceOrder.getYsfyId())){
            TadvancesReceived tadvancesReceived = tadvancesReceivedService.get(serviceOrder.getYsfyId());
            // 子表-预计
            List < TadvancesReceivedEstimated > tadvancesReceivedEstimatedList = tadvancesReceived.getTadvancesReceivedEstimatedList();
            // 子表-实际
            List < TadvancesReceivedActual > tadvancesReceivedActualList = tadvancesReceived.getTadvancesReceivedActualList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedEstimatedList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedEstimated.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedEstimated.getFrameNumber())) {
                            tadvancesReceivedEstimated.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
                for (TadvancesReceivedActual tadvancesReceivedActual : tadvancesReceivedActualList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedActual.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedActual.getFrameNumber())) {
                            tadvancesReceivedActual.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tadvancesReceivedService.save(tadvancesReceived);
        }
        // 保证金预收 回写
        if (StringUtils.isNotEmpty(serviceOrder.getBzjYusId())){
            TadvancesReceived tadvancesReceived = tadvancesReceivedService.get(serviceOrder.getBzjYusId());
            // 子表-预计
            List < TadvancesReceivedEstimated > tadvancesReceivedEstimatedList = tadvancesReceived.getTadvancesReceivedEstimatedList();
            // 子表-实际
            List < TadvancesReceivedActual > tadvancesReceivedActualList = tadvancesReceived.getTadvancesReceivedActualList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedEstimatedList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedEstimated.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedEstimated.getFrameNumber())) {
                            tadvancesReceivedEstimated.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
                for (TadvancesReceivedActual tadvancesReceivedActual : tadvancesReceivedActualList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedActual.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedActual.getFrameNumber())) {
                            tadvancesReceivedActual.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tadvancesReceivedService.save(tadvancesReceived);
        }
        // 代理费预收 回写
        if (StringUtils.isNotEmpty(serviceOrder.getDlfYusId())){
            TadvancesReceived tadvancesReceived = tadvancesReceivedService.get(serviceOrder.getDlfYusId());
            // 子表-预计
            List < TadvancesReceivedEstimated > tadvancesReceivedEstimatedList = tadvancesReceived.getTadvancesReceivedEstimatedList();
            // 子表-实际
            List < TadvancesReceivedActual > tadvancesReceivedActualList = tadvancesReceived.getTadvancesReceivedActualList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedEstimatedList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedEstimated.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedEstimated.getFrameNumber())) {
                            tadvancesReceivedEstimated.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
                for (TadvancesReceivedActual tadvancesReceivedActual : tadvancesReceivedActualList) {
                    if (ladingBillDetail.getRowNumber().equals(tadvancesReceivedActual.getRowNumber())) {
                        if (StringUtils.isEmpty(tadvancesReceivedActual.getFrameNumber())) {
                            tadvancesReceivedActual.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tadvancesReceivedService.save(tadvancesReceived);
        }
        // 保证金预付 回写
        if (StringUtils.isNotEmpty(serviceOrder.getBzjYufId())){
            Tprepayment tprepayment = tprepaymentService.get(serviceOrder.getBzjYufId());
            // 子表-预计
            List < TprepaymentEstimated > tprepaymentEstimatedList = tprepayment.getTprepaymentEstimatedList();
            // 子表-实际
            List < TprepaymentActual > tprepaymentActualList = tprepayment.getTprepaymentActualList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TprepaymentEstimated tprepaymentEstimated : tprepaymentEstimatedList) {
                    if (ladingBillDetail.getRowNumber().equals(tprepaymentEstimated.getRowNumber())) {
                        if (StringUtils.isEmpty(tprepaymentEstimated.getFrameNumber())) {
                            tprepaymentEstimated.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
                for (TprepaymentActual tprepaymentActual : tprepaymentActualList) {
                    if (ladingBillDetail.getRowNumber().equals(tprepaymentActual.getRowNumber())) {
                        if (StringUtils.isEmpty(tprepaymentActual.getFrameNumber())) {
                            tprepaymentActual.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tprepaymentService.save(tprepayment);
        }
        // 代理费预付 回写
        if (StringUtils.isNotEmpty(serviceOrder.getDlfYufId())){
            Tprepayment tprepayment = tprepaymentService.get(serviceOrder.getDlfYufId());
            // 子表-预计
            List < TprepaymentEstimated > tprepaymentEstimatedList = tprepayment.getTprepaymentEstimatedList();
            // 子表-实际
            List < TprepaymentActual > tprepaymentActualList = tprepayment.getTprepaymentActualList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TprepaymentEstimated tprepaymentEstimated : tprepaymentEstimatedList) {
                    if (ladingBillDetail.getRowNumber().equals(tprepaymentEstimated.getRowNumber())) {
                        if (StringUtils.isEmpty(tprepaymentEstimated.getFrameNumber())) {
                            tprepaymentEstimated.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
                for (TprepaymentActual tprepaymentActual : tprepaymentActualList) {
                    if (ladingBillDetail.getRowNumber().equals(tprepaymentActual.getRowNumber())) {
                        if (StringUtils.isEmpty(tprepaymentActual.getFrameNumber())) {
                            tprepaymentActual.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tprepaymentService.save(tprepayment);
        }
        // 代理费应收 回写
        if (StringUtils.isNotEmpty(serviceOrder.getDlfYisId())){
            Tar tar = tarService.get(serviceOrder.getDlfYisId());
            List < TarDetail > tarDetailList = tar.getTarDetailList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TarDetail tarDetail : tarDetailList) {
                    if (ladingBillDetail.getRowNumber().equals(tarDetail.getRowNumber())) {
                        if (StringUtils.isEmpty(tarDetail.getFrameNumber())) {
                            tarDetail.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tarService.save(tar);
        }
        // 代理费应付 回写
        if (StringUtils.isNotEmpty(serviceOrder.getDlfYifId())) {
            Tap tap = tapService.get(serviceOrder.getDlfYifId());
            List < TapDetail > tapDetailList = tap.getTapDetailList();
            for (LadingBillDetail ladingBillDetail : ladingBillDetails) {
                for (TapDetail tapDetail : tapDetailList) {
                    if (ladingBillDetail.getRowNumber().equals(tapDetail.getRowNumber())) {
                        if (StringUtils.isEmpty(tapDetail.getFrameNumber())) {
                            tapDetail.setFrameNumber(ladingBillDetail.getFrameNumber());
                        }
                    }
                }
            }
            tapService.save(tap);
        }
	}
	
	/**
	 * 更新状态
	 * @param ladingBill
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(LadingBill ladingBill) {
		super.updateStatus(ladingBill);
	}
	
	/**
	 * 删除数据
	 * @param ladingBill
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(LadingBill ladingBill) {
		super.delete(ladingBill);
		LadingBillDetail ladingBillDetail = new LadingBillDetail();
		ladingBillDetail.setLadingBillId(ladingBill);
		ladingBillDetailDao.deleteByEntity(ladingBillDetail);
	}

    public Integer findListDetail(String serviceOrderId) {
	    return ladingBillDetailDao.findListDetail(serviceOrderId);
    }
}